/**
 * 
 */
package wong.board.client.ui;

import java.util.Set;

import wong.board.client.widgets.Button;
import wong.board.client.widgets.Button.ButtonCallback;
import wong.board.client.widgets.ContentForm.FormCallback;
import wong.board.client.widgets.HasButtonCallbacks;
import wong.board.client.widgets.HasFormCallbacks;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.DomEvent;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;

/**
 * @author wong
 * 
 */
public class SearchPresenter extends Presenter<SearchPresenter.View, JSONObject> {
	private ViewHandler handler;

	public SearchPresenter() {
		this((View) GWT.create(View.class));
	}

	public SearchPresenter(View view) {
		super(view);
	}

	@Override
	protected void onViewAttached() {
		super.onViewAttached();
		handler = new ViewHandler();
		getView().getFormCallbacks().addCallback(handler);
		getView().getResultCloseButtonCallbacks().addCallback(handler);
	}

	@Override
	protected void onViewDetached() {
		getView().getFormCallbacks().removeCallback(handler);
		getView().getResultCloseButtonCallbacks().removeCallback(handler);
		handler = null;
		super.onViewDetached();
	}

	@Override
	public void updateView(JSONObject search) {
		// getView().resetView();
		//
		Set<String> keySet = search.keySet();
		for (String key : keySet) {
			JSONArray value = search.get(key).isArray();
			getView().addEngine(key, value.get(0).isString().stringValue(),
					value.get(1).isBoolean().booleanValue());
		}
	}

	/* */

	private class ViewHandler implements FormCallback, ButtonCallback<String> {

		@Override
		public boolean onSubmit() {
			getView().showResults();
			return false;
		}

		@Override
		public void onReset() {
			getView().hideResults();
		}

		@Override
		public void onInput(NativeEvent nativeEvent) {
			getView().hideResultsOnEmptySearch();
		}

		@Override
		public void onChange(NativeEvent nativeEvent) {
			getView().hideResultsOnEmptySearch();
		}

		@Override
		public void onInvalid() {
			getView().hideResultsOnEmptySearch();
		}

		@Override
		public void onAction(Button<String> button, DomEvent<?> event) {
			if (button.getValue().equals(View.ID_CLOSE)) {
				getView().hideResults();
			}
		}
	}

	public interface View extends Presenter.View {
		public static final String ID_CLOSE = "close";

		void resetView();

		void addEngine(String name, String query, boolean selected);

		void showResults();

		void hideResults();

		void hideResultsOnEmptySearch();

		HasFormCallbacks getFormCallbacks();

		HasButtonCallbacks<String> getResultCloseButtonCallbacks();

	}

}
